package com.mycompany.myapp.web.rest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.mycompany.myapp.IntegrationTest;
import com.mycompany.myapp.domain.UserClass;
import com.mycompany.myapp.repository.UserClassRepository;
import com.mycompany.myapp.service.dto.UserClassDTO;
import com.mycompany.myapp.service.mapper.UserClassMapper;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link UserClassResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class UserClassResourceIT {

    private static final Integer DEFAULT_CLASS_ID = 1;
    private static final Integer UPDATED_CLASS_ID = 2;

    private static final Instant DEFAULT_START_TIME = Instant.ofEpochMilli(0L);
    private static final Instant UPDATED_START_TIME = Instant.now().truncatedTo(ChronoUnit.MILLIS);

    private static final Instant DEFAULT_END_TIME = Instant.ofEpochMilli(0L);
    private static final Instant UPDATED_END_TIME = Instant.now().truncatedTo(ChronoUnit.MILLIS);

    private static final Integer DEFAULT_CLASS_NUMBER = 1;
    private static final Integer UPDATED_CLASS_NUMBER = 2;

    private static final Integer DEFAULT_CLASS_STATUS = 1;
    private static final Integer UPDATED_CLASS_STATUS = 2;

    private static final String ENTITY_API_URL = "/api/user-classes";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private UserClassRepository userClassRepository;

    @Autowired
    private UserClassMapper userClassMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restUserClassMockMvc;

    private UserClass userClass;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static UserClass createEntity(EntityManager em) {
        UserClass userClass = new UserClass()
            .classId(DEFAULT_CLASS_ID)
            .startTime(DEFAULT_START_TIME)
            .endTime(DEFAULT_END_TIME)
            .classNumber(DEFAULT_CLASS_NUMBER)
            .classStatus(DEFAULT_CLASS_STATUS);
        return userClass;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static UserClass createUpdatedEntity(EntityManager em) {
        UserClass userClass = new UserClass()
            .classId(UPDATED_CLASS_ID)
            .startTime(UPDATED_START_TIME)
            .endTime(UPDATED_END_TIME)
            .classNumber(UPDATED_CLASS_NUMBER)
            .classStatus(UPDATED_CLASS_STATUS);
        return userClass;
    }

    @BeforeEach
    public void initTest() {
        userClass = createEntity(em);
    }

    @Test
    @Transactional
    void createUserClass() throws Exception {
        int databaseSizeBeforeCreate = userClassRepository.findAll().size();
        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);
        restUserClassMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userClassDTO)))
            .andExpect(status().isCreated());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeCreate + 1);
        UserClass testUserClass = userClassList.get(userClassList.size() - 1);
        assertThat(testUserClass.getClassId()).isEqualTo(DEFAULT_CLASS_ID);
        assertThat(testUserClass.getStartTime()).isEqualTo(DEFAULT_START_TIME);
        assertThat(testUserClass.getEndTime()).isEqualTo(DEFAULT_END_TIME);
        assertThat(testUserClass.getClassNumber()).isEqualTo(DEFAULT_CLASS_NUMBER);
        assertThat(testUserClass.getClassStatus()).isEqualTo(DEFAULT_CLASS_STATUS);
    }

    @Test
    @Transactional
    void createUserClassWithExistingId() throws Exception {
        // Create the UserClass with an existing ID
        userClass.setId(1L);
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        int databaseSizeBeforeCreate = userClassRepository.findAll().size();

        // An entity with an existing ID cannot be created, so this API call must fail
        restUserClassMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userClassDTO)))
            .andExpect(status().isBadRequest());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void getAllUserClasses() throws Exception {
        // Initialize the database
        userClassRepository.saveAndFlush(userClass);

        // Get all the userClassList
        restUserClassMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(userClass.getId().intValue())))
            .andExpect(jsonPath("$.[*].classId").value(hasItem(DEFAULT_CLASS_ID)))
            .andExpect(jsonPath("$.[*].startTime").value(hasItem(DEFAULT_START_TIME.toString())))
            .andExpect(jsonPath("$.[*].endTime").value(hasItem(DEFAULT_END_TIME.toString())))
            .andExpect(jsonPath("$.[*].classNumber").value(hasItem(DEFAULT_CLASS_NUMBER)))
            .andExpect(jsonPath("$.[*].classStatus").value(hasItem(DEFAULT_CLASS_STATUS)));
    }

    @Test
    @Transactional
    void getUserClass() throws Exception {
        // Initialize the database
        userClassRepository.saveAndFlush(userClass);

        // Get the userClass
        restUserClassMockMvc
            .perform(get(ENTITY_API_URL_ID, userClass.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(userClass.getId().intValue()))
            .andExpect(jsonPath("$.classId").value(DEFAULT_CLASS_ID))
            .andExpect(jsonPath("$.startTime").value(DEFAULT_START_TIME.toString()))
            .andExpect(jsonPath("$.endTime").value(DEFAULT_END_TIME.toString()))
            .andExpect(jsonPath("$.classNumber").value(DEFAULT_CLASS_NUMBER))
            .andExpect(jsonPath("$.classStatus").value(DEFAULT_CLASS_STATUS));
    }

    @Test
    @Transactional
    void getNonExistingUserClass() throws Exception {
        // Get the userClass
        restUserClassMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putNewUserClass() throws Exception {
        // Initialize the database
        userClassRepository.saveAndFlush(userClass);

        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();

        // Update the userClass
        UserClass updatedUserClass = userClassRepository.findById(userClass.getId()).get();
        // Disconnect from session so that the updates on updatedUserClass are not directly saved in db
        em.detach(updatedUserClass);
        updatedUserClass
            .classId(UPDATED_CLASS_ID)
            .startTime(UPDATED_START_TIME)
            .endTime(UPDATED_END_TIME)
            .classNumber(UPDATED_CLASS_NUMBER)
            .classStatus(UPDATED_CLASS_STATUS);
        UserClassDTO userClassDTO = userClassMapper.toDto(updatedUserClass);

        restUserClassMockMvc
            .perform(
                put(ENTITY_API_URL_ID, userClassDTO.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userClassDTO))
            )
            .andExpect(status().isOk());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
        UserClass testUserClass = userClassList.get(userClassList.size() - 1);
        assertThat(testUserClass.getClassId()).isEqualTo(UPDATED_CLASS_ID);
        assertThat(testUserClass.getStartTime()).isEqualTo(UPDATED_START_TIME);
        assertThat(testUserClass.getEndTime()).isEqualTo(UPDATED_END_TIME);
        assertThat(testUserClass.getClassNumber()).isEqualTo(UPDATED_CLASS_NUMBER);
        assertThat(testUserClass.getClassStatus()).isEqualTo(UPDATED_CLASS_STATUS);
    }

    @Test
    @Transactional
    void putNonExistingUserClass() throws Exception {
        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();
        userClass.setId(count.incrementAndGet());

        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restUserClassMockMvc
            .perform(
                put(ENTITY_API_URL_ID, userClassDTO.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userClassDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchUserClass() throws Exception {
        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();
        userClass.setId(count.incrementAndGet());

        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserClassMockMvc
            .perform(
                put(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userClassDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamUserClass() throws Exception {
        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();
        userClass.setId(count.incrementAndGet());

        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserClassMockMvc
            .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userClassDTO)))
            .andExpect(status().isMethodNotAllowed());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateUserClassWithPatch() throws Exception {
        // Initialize the database
        userClassRepository.saveAndFlush(userClass);

        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();

        // Update the userClass using partial update
        UserClass partialUpdatedUserClass = new UserClass();
        partialUpdatedUserClass.setId(userClass.getId());

        partialUpdatedUserClass.classId(UPDATED_CLASS_ID).classNumber(UPDATED_CLASS_NUMBER).classStatus(UPDATED_CLASS_STATUS);

        restUserClassMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedUserClass.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedUserClass))
            )
            .andExpect(status().isOk());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
        UserClass testUserClass = userClassList.get(userClassList.size() - 1);
        assertThat(testUserClass.getClassId()).isEqualTo(UPDATED_CLASS_ID);
        assertThat(testUserClass.getStartTime()).isEqualTo(DEFAULT_START_TIME);
        assertThat(testUserClass.getEndTime()).isEqualTo(DEFAULT_END_TIME);
        assertThat(testUserClass.getClassNumber()).isEqualTo(UPDATED_CLASS_NUMBER);
        assertThat(testUserClass.getClassStatus()).isEqualTo(UPDATED_CLASS_STATUS);
    }

    @Test
    @Transactional
    void fullUpdateUserClassWithPatch() throws Exception {
        // Initialize the database
        userClassRepository.saveAndFlush(userClass);

        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();

        // Update the userClass using partial update
        UserClass partialUpdatedUserClass = new UserClass();
        partialUpdatedUserClass.setId(userClass.getId());

        partialUpdatedUserClass
            .classId(UPDATED_CLASS_ID)
            .startTime(UPDATED_START_TIME)
            .endTime(UPDATED_END_TIME)
            .classNumber(UPDATED_CLASS_NUMBER)
            .classStatus(UPDATED_CLASS_STATUS);

        restUserClassMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedUserClass.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedUserClass))
            )
            .andExpect(status().isOk());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
        UserClass testUserClass = userClassList.get(userClassList.size() - 1);
        assertThat(testUserClass.getClassId()).isEqualTo(UPDATED_CLASS_ID);
        assertThat(testUserClass.getStartTime()).isEqualTo(UPDATED_START_TIME);
        assertThat(testUserClass.getEndTime()).isEqualTo(UPDATED_END_TIME);
        assertThat(testUserClass.getClassNumber()).isEqualTo(UPDATED_CLASS_NUMBER);
        assertThat(testUserClass.getClassStatus()).isEqualTo(UPDATED_CLASS_STATUS);
    }

    @Test
    @Transactional
    void patchNonExistingUserClass() throws Exception {
        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();
        userClass.setId(count.incrementAndGet());

        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restUserClassMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, userClassDTO.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(userClassDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchUserClass() throws Exception {
        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();
        userClass.setId(count.incrementAndGet());

        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserClassMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(userClassDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamUserClass() throws Exception {
        int databaseSizeBeforeUpdate = userClassRepository.findAll().size();
        userClass.setId(count.incrementAndGet());

        // Create the UserClass
        UserClassDTO userClassDTO = userClassMapper.toDto(userClass);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserClassMockMvc
            .perform(
                patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(userClassDTO))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the UserClass in the database
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteUserClass() throws Exception {
        // Initialize the database
        userClassRepository.saveAndFlush(userClass);

        int databaseSizeBeforeDelete = userClassRepository.findAll().size();

        // Delete the userClass
        restUserClassMockMvc
            .perform(delete(ENTITY_API_URL_ID, userClass.getId()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<UserClass> userClassList = userClassRepository.findAll();
        assertThat(userClassList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
